import { Button, Card, Dropdown, Input, Popconfirm, Space, Spin, Table, Tree, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { useState, useEffect, useRef } from 'react'
import Api from '../../../../../utils/api';
import CztApi from '../../../../../utils/apis/CztApi'
import dynamicColumnApi from '../../../../../utils/apis/dynamicColumnApi';
import _ from 'lodash';
import ScrollTable from '../../../../common/ScrollTable';
import { data } from 'browserslist';
import { BrowserRouter, Route } from 'react-router-dom';
import CztEdit from '../CztHandle/CztEdit';
import { useHistory, Switch } from 'react-router-dom';
import pubsub from 'pubsub-js';
import FetchHelper from '../../../../../utils/helper/fetch-helper';

export default function Czt(props) {
    const [category, setCategory] = useState();
    const [colorStyel, setColorStyel] = useState();
    const [cztData, setCztData] = useState();
    const [category2, setCategory2] = useState();
    const [total, setTotal] = useState();
    const [allColumns, setAllColumns] = useState();
    const [loading, setLoading] = useState();
    const rootRef = useRef();

    const [params, setParams] = useState({
        pageSize: 10,
        pageNum: 1,
        cztMiddle: '公共服务设施'
    });

    useEffect(() => {
        Api.getCztCategroy().then(datas => {
            setCategory(datas)
        })
    }, [])

    useEffect(() => {
        Api.getCztCategroy2().then(datas => {
            setCategory2(datas)

        })
    }, [])

    useEffect(() => {
        dynamicColumnApi.czt().then(data => {
            setAllColumns(data);
        })
    }, [])

    const [cztzl, setCztzl] = useState(null)
    const [node, setNode] = useState(null);
    // console.log('cztzl', cztzl)
    // console.log('node',node)
const [value,setValue]=useState();

    useEffect(() => {
        setLoading(true);
        let promise;
        if (cztzl) {
            promise = CztApi.list()
        } else {
            promise = CztApi.list(node?.key)
        }
        // setCztzl(null)
        promise.then(resp => {
            if(value){
                const filterData=resp?.rows.filter(item=>item?.cztmc.includes(value))
                setCztData(filterData)
            }else{
                setCztData(resp.rows)
            }
            
            setTotal(resp.total);

        }).finally(e => {
            setLoading(false)
        })
        setCztzl(null)
    }, [cztzl, node,value])
    // console.log('cztData', cztData)

    //新增

    const items = category2
    // 导出数据地址
    // const url = '/admin-api/ybyj/cztjcb/exportLike?columnNames=cztzl&key=公共服务设施';


    const tableCols = allColumns?.[params.cztSmall || params.cztMiddle] || [];
    //Excel表导入
    const message = '';

    props = {
        name: 'file',
        action: '/admin-api/ybyj/cztjcb/import',
        headers: {
            authorization: 'authorization-text',
        },

        // onChange(info) {
        //     if (info.file.status !== 'uploading') {
        //         console.log(info.file, info.fileList);
        //     }
        //     if (info.file.status === 'done') {
        //         message.success(`${info.file.name} 文件上传成功`);

        //     } else if (info.file.status === 'error') {
        //         message.error(`${info.file.name} 文件上传失败`);
        //     }
        // },
    };
    //编辑
    //设置按键跳转路径
    const history = useHistory();
    const cztHandleEdit = (record) => {
        history.push(`/manager/cztEdit/${record.id}`)

    }

    //查看

    const cztHandleLook = (record) => {
        history.push(`/manager/cztLook/${record.id}`)
    }

    //新增
    // const [key,setKey]=useState()
    const [keyPath, setKeyPath] = useState();
    const cztAddDatas = (keyPath) => {
        // history.push(`/manager/cztAdd/${keyPath[2]}--${keyPath[1]}--${keyPath[0]}`)
        history.push(`/manager/cztAdd/${keyPath}`)
    }

    //删除按键

    const deleteHandle = (record) => {

        const newcztData = cztData.filter(function (arr) {
            return arr.id !== record.id
        })

        FetchHelper.deleteJson(`/admin-api/ybyj/cztjcb/` + record.id).then(() => alert('删除成功')).catch(error => alert("删除失败") + error)


        setCztData(newcztData)
    }
    // debugger
    //搜索
    const formCztData = cztData

    const onSearch = (value) => {
        setValue(value)
        setParams(params => {
            // console.log(params)
            return {
                ...params,
                cztmc: value,
                pageNum: 1
            }
        });

    }
    // console.log('params',params)
    // const [messageApi,contentHolder]=Message.useMessage();

    const handleJudge = (node, keyPath) => {
        if (node?.tag !== "cztxl") {
            window.alert('请选择小类')
        }
        else {
            const keyPath = node?.key
            cztAddDatas(keyPath)
        }
    }

    return <div className='layout-h h100'>
        <Card size='small' className='h100' style={{
            width: 240,
            marginRight: 12,
            overflowX: "auto",
            overflowY: "auto"

        }} title={"调查对象分类"}>
            {category && <Tree className='categray-tree' selectedKeys={[params.cztSmall || params.cztMiddle]}
                treeData={category} blockNode
                defaultExpandAll
                rootStyle={{color:'#aaa'}}
                onSelect={(selectedKeys, { node }) => {
                   
                    setNode(node)
                    if (node.children) {
                        setCztzl(selectedKeys?.[0]);
                    }

                    const p = {}
                    if (node.children) {
                        p.cztMiddle = selectedKeys?.[0]
                    } else {
                        p.cztSmall = selectedKeys?.[0]
                    }

                    setParams(params => {
                        return {
                            pageSize: params.pageSize,
                            pageNum: 1,
                            ...p
                        }
                    })
                    // fetch(`/admin-api/ybyj/cztjcb/exportLike?columnNames=${node.tag}&key=${node.title}`,{
                    //             method:'POST',
                    //             headers:{
                    //                 'Content-Type':'application/json;charset=UTF-8'
                    //             }
                    //         }).then(response=>response.blob()).then(blob=>{
                    //             const a=document.createElement("a");
                    //             a.download="data.xls";
                    //             a.href=URL.createObjectURL(blob);
                    //             a.click();
                    //         }).catch(error=>console.log(error))
                }}
                fieldNames={{
                    title: 'title',
                    key: 'title'
                }}
            // onChange={({node})=>{
            //     fetch(`/admin-api/ybyj/cztjcb/exportLike?columnNames=cztxl&key=${node}`,{
            //         method:'POST',
            //         headers:{
            //             'Content-Type':'application/json;charset=UTF-8'
            //         }
            //     }).then(response=>response.blob()).then(blob=>{
            //         const a=document.createElement("a");
            //         a.download="data.xls";
            //         a.href=URL.createObjectURL(blob);
            //         a.click();
            //     }).catch(error=>console.log(error))
            // }}
            />}

        </Card>
        <Card size="small" className='h100 fill w0' style={{
            position: "relative",
        }} bodyStyle={{

            display: "flex",
            flexDirection: "column",
            height: "100%"
        }}>
            <div style={{
                marginBottom: 12,
                display: 'flex',
                alignItems: "center",
                justifyContent: "space-between"
            }}>

                <Space>
                    <>
                        <Button onClick={() => handleJudge(node, keyPath)}>新增</Button>
                        <Upload {...props}>
                            <Button icon={<UploadOutlined />}>数据导入</Button>
                        </Upload>
                        {/* <Button type="primary" key="download" onClick={() => {
                            fetch(`/admin-api/ybyj/cztjcb/exportLike?columnNames=${node?.tag}&key=${node.key}`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json;charset=UTF-8'
                                }
                            }).then(response => response.blob()).then(blob => {
                                const a = document.createElement("a");
                                a.download = "data.xls";
                                a.href = URL.createObjectURL(blob);
                                a.click();
                            }).catch(error => console.log(error))
                        }}>数据导出</Button> */}
                    </>
                </Space>

                <div>
                    <Input.Search placeholder='输入名称查找'
                        allowClear
                        enterButton={true}
                        onSearch={onSearch}
                    />
                </div>
            </div>

            {/* {loading && <div style={{
                position: 'absolute',
                left: 0,
                bottom: 0,
                right: 0,
                top: 0,
                display: 'flex',
                alignItems: "center",
                justifyContent: "center"
            }}>
                <Spin />
            </div>} */}

            <div ref={rootRef} className="fill h0">
                {<ScrollTable style={{
                    // border:"1px solid #ddd"
                }}
                    loading={loading}
                    parentNode={rootRef.current}
                    size='small'
                    bordered
                    dataSource={cztData}
                    scroll={{
                        x: 320 + _.sumBy(tableCols, 'width'),
                    }}
                    columns={[
                        {
                            title: '名称',
                            dataIndex: 'jgmc',
                            fixed: 'left',
                            key: 'jgmc',
                            width: 160
                            // render:(text)=>{
                            //     return text
                            // }
                        },
                        {
                            title: '地址',
                            dataIndex: 'jgxxdz',
                            fixed: 'left',
                            width: 160
                            // render:(text)=>{
                            //     return text
                            // }
                        },
                        ...tableCols,
                        // {
                        //     title: '详情',
                        //     // dataIndex: 'xq',
                        //     // fixed: 'left',
                        //     width: 160,
                        //     render: (text, record) => {
                        //         return <Space size="middle">
                        //             <Button onClick={e => { cztHandleXq(record) }} type='link'>详情</Button>

                        //         </Space>

                        //     }
                        //     // render:(text)=>{
                        //     //     return text
                        //     // }
                        // },
                        {
                            title: '操作',
                            key: 'caozuo',
                            width: 260,
                            fixed: "right",
                            render: (text, record) => {
                                return <Space size="middle">
                                    <Button onClick={e => { cztHandleLook(record) }}>查看</Button>

                                    <Button onClick={e => { cztHandleEdit(record) }}>编辑</Button>

                                    <Popconfirm title="确定删除吗?" onConfirm={e => deleteHandle(record)}>
                                        {/* <Button onComfir={e => { deleteHandle(record) }}>删除</Button> */}
                                        <Button>删除</Button>
                                    </Popconfirm>
                                </Space>

                            }
                        },

                    ].map(item => {
                        return {
                            ...item,
                            // ellipsis: {
                            //     showTitle: false
                            // }
                        }
                    })}

                    pagination={{
                        current: params.pageNum,
                        pageSize: params.pageSize,
                        total,

                        // simple: true
                    }}
                    onChange={({ current }) => {
                        setParams(params => {
                            return {
                                ...params,
                                pageNum: current
                            }
                        })
                    }}
                // size='small'
                />}
            </div>
        </Card>
    </div>;
}